const WXAPI = require('apifm-wxapi')
const app = getApp();

// 检测登录状态，返回 true / false
async function checkHasLogined() {
  const token = wx.getStorageSync('token')
  if (!token) {
    return false
  }
  wx.checkSession({
    fail() {
      return false
    }
  })
  
  const checkTokenRes = await WXAPI.checkToken(token)
  if (checkTokenRes.retCode !== '200') {
    wx.removeStorageSync('token')
    return false
  }

  return true
}


function confirmLogin(){
  wx.showModal({
    title: '提示',
    content: '本次操作需要您的登录授权',
    cancelText: '暂不登录',
    confirmText: '前往登录',
    success(res) {
      if (res.confirm) {
        wx.switchTab({
          url: "/pages/my/index"
        })
      } else {
        if (getCurrentPages().length == 1) {
          wx.switchTab({
            url: "/pages/index/index"
          })
        } else {
          wx.navigateBack()
        }
      }
    }
  })
}

async function login(page, data){
  const _this = this
  wx.login({
    success: function (res) {
      WXAPI.login_wx(res.code).then(function (res) {
        if (res.code == 10000) {
          // 去注册
          _this.register(page)
          return;
        }
        if (res.retCode != 200) {
          // 登录错误
          wx.showModal({
            title: '错误',
            content: '无法登录，请重试:' + res.msg,
            showCancel: false
          })
          return;
        }
        
        wx.setStorageSync('token', res.data.tokenStr)
        WXAPI.updateUser({...data}).then((res) => {
          if(res.retCode === '200'){
            //获取用户信息
            WXAPI.getCurrentUser().then((res) => {
              console.log('--res',res)
              if(res.retCode === '200'){
                wx.setStorageSync('curUserInfo', res.data);
                if(!wx.getStorageSync('_curShop')){
                  //没有所选商铺 默认选择第一个
                  const { merShopInfos } = res.data
                  wx.setStorageSync('_curShop', merShopInfos ? merShopInfos[0] : '');
                }
                if(res.data.merShopInfos && res.data.merShopInfos.length >0){
                  app.globalData.shopNo = res.data.merShopInfos[0].shopNo;
                }
                wx.setStorageSync('uid', res.data.unionid)
                  if ( page ) {
                    page.onShow()
                  }
              }else{
                wx.showToast({
                  title: res.retMsg
                })
              }
            })
            
          }
        })
        // WXAPI.checkToken().then((res) => {
        //   if(res.retCode === '200')
          // wx.setStorageSync('uid', res.data.unionid)
          // if ( page ) {
          //   page.onShow()
          // }
        // })
        
      })
    }
  })
}

async function register(page) {
  let _this = this;
  wx.login({
    success: function (res) {
      let code = res.code; // 微信登录接口返回的 code 参数，下面注册接口需要用到
      wx.getUserInfo({
        success: function (res) {
          let iv = res.iv;
          let encryptedData = res.encryptedData;
          let referrer = '' // 推荐人
          let referrer_storge = wx.getStorageSync('referrer');
          if (referrer_storge) {
            referrer = referrer_storge;
          }
          // 下面开始调用注册接口
          WXAPI.register_complex({
            code: code,
            encryptedData: encryptedData,
            iv: iv,
            referrer: referrer
          }).then(function (res) {
            _this.login(page);
          })
        }
      })
    }
  })
}

function loginOut(){
  wx.removeStorageSync('token')
  wx.removeStorageSync('uid')
  wx.removeStorageSync('userInfo')
}

module.exports = {
  checkHasLogined: checkHasLogined,
  login: login,
  register: register,
  loginOut: loginOut,
  confirmLogin: confirmLogin
}